<template>
    <PopList :title="'CesiumLab4'" :showButton="true" :link="'http://bjxbsj.cn'" @ok="ok">
        <LabelInput v-model="cesiumLabUrl" :label="'服务地址'" @blur="initNewList" @keydownenter="initNewList">
        </LabelInput>
        <div class="images_bottom_content">
            <div class="images_servelocation">
                <label>token</label>
                <div class="server_token" v-if="!tokenInputShow" @click="tokenInputShow = true">{{ cesiumLabToken }}
                </div>
                <input v-else type="text" v-model="cesiumLabToken" @blur="changeToken" @keydown.enter="changeToken">
            </div>
            <!-- <div class="images_servelocation" v-if="geographicalScope">
                <label>地理范围</label>
                <div class="images_servelocation_readonly">{{ geographicalScope }}</div>
            </div> -->
        </div>
        <div class="server_lab">
            <div class="server_lab_title">
                <div class="server_lab_title_index">{{ '序号' }}</div>
                <div class="server_lab_title_name">{{ '名称' }}</div>
                <!-- <div class="server_lab_title_server">{{ '服务地址' }}</div> -->
                <div class="server_lab_title_type">{{ '类型' }}</div>
            </div>
            <div class="server_content">
                <div class="server_lab_content" v-for="(item, index) in serverList"
                    @click="changeServerLab(item, index)" :key="index"
                    :class="{ 'server_lab_content_active': serverActive === index }">
                    <div class="server_lab_content_index">{{ index + 1 }}</div>
                    <div class="server_lab_content_name">{{ item.name }}</div>
                    <!-- <div class="server_lab_content_server">{{ item.serverUrl }}</div> -->
                    <div class="server_lab_content_type">{{ item.type }}</div>
                </div>
            </div>
        </div>
        <div class="images_servelocation" v-if="serverUrl">
            <label>url</label>
            <div class="images_servelocation_readonly">{{ serverUrl }}</div>
        </div>
        <div class="images_servelocation" v-if="MaximumLevel">
            <label>最大级别</label>
            <div class="images_servelocation_readonly">{{ MaximumLevel }}</div>
        </div>
    </PopList>
</template>
<script setup lang="ts">
import { inject, onBeforeUnmount, onMounted, ref } from 'vue';
import { createVueDisposer, toVR } from 'vue-xe2-plugin/dist-node/components/xe2/tools';
import PopList from "../../../components/PopList.vue";
import { XbsjEarthUi } from '../../../scripts/xbsjEarthUi';
import { postSetToken } from '../../../api/service';
import LabelInput from "../../../components/LabelInput.vue"
import { Message } from "earthsdk-ui"
import { imageType, terrainType, modelType, imageServe, createModel, createTerrain, createImage } from "./tools"
const d = createVueDisposer(onBeforeUnmount)
const xbsjEarthUi = inject('xbsjEarthUi') as XbsjEarthUi
const cesiumLabUrl = toVR<string>(d, [xbsjEarthUi, 'cesiumLabUrl'])
const cesiumLabToken = toVR<string>(d, [xbsjEarthUi, 'cesiumLabToken'])
// const token = ref()
const tokenInputShow = ref(false)
const serverActive = ref(-1)
const serverUrl = ref('')//
const MaximumLevel = ref()//最大级别
const geographicalScope = ref('')//地理范围
const currentItem = ref<imageServe>()
const emits = defineEmits(['close']);
const changeServerLab = (item: imageServe, index: number) => {
    currentItem.value = item
    serverActive.value = index
    serverUrl.value = item.serverUrl
    MaximumLevel.value = item.MaximumLevel
    geographicalScope.value = item.geographicalScope
}

const serverList = ref<imageServe[]>([])
const ok = () => {
    if (!cesiumLabUrl.value) {
        Message.warning('服务地址为空，请填写地址')
        return
    }
    if (!serverUrl.value) {
        Message.warning('未选择服务，请先选择')
        return
    }
    if (!currentItem.value) return
    if (currentItem.value.type === '影像') {
        createImage(currentItem.value, xbsjEarthUi)
    } else if (currentItem.value.type === '模型') {
        createModel(currentItem.value, xbsjEarthUi)
    } else if (currentItem.value.type === '地形') {
        createTerrain(currentItem.value, xbsjEarthUi)
    }
}
const initNewList = async () => {
    let newList: imageServe[] = []
    if (!cesiumLabUrl.value) {
        Message.warning('服务地址为空，请填写地址')
        return
    }
    // if (!cesiumLabToken.value) {
    //     Message.warning('请填写服务token');
    //     return
    // }
    let url
    if (cesiumLabToken.value) {
        url = `${cesiumLabUrl.value}/tile/services/labtoken?labtoken=${cesiumLabToken.value}`
    }else{
        url = `${cesiumLabUrl.value}/tile/statistics/services/all/auth`
    }
    const token = localStorage.getItem('token') as string | undefined
    // console.log(token);

    postSetToken(url, cesiumLabToken.value ? undefined : token).then(((res: any) => {
        // console.log(res);
        if (res && res.code === 1000) {
            const images = res.data.images
            const models = res.data.models
            const terrains = res.data.terrains
            images.forEach((item: imageType) => {
                const li: imageServe = {
                    type: '影像',
                    name: item.name,
                    serverUrl: (item.tiletrans === "tms" ? `${cesiumLabUrl.value}/tile/image/tms/${item.id}/tilemapresource.xml` : `${cesiumLabUrl.value}/tile/image/wmts/${item.id}/{z}/{x}/{y}`),
                    createTime: item.createTime,
                    MaximumLevel: item.maxzoom,
                    geographicalScope: `${item.west.toFixed(4)}，${item.south.toFixed(4)}，${item.east.toFixed(4)}，${item.north.toFixed(4)}`,
                    rectangle: [item.west, item.south, item.east, item.north],
                    czmTilingScheme: item.proj === 4326 ? "GeographicTilingScheme" : "WebMercatorTilingScheme",
                    czmMinimumLevel: Number(item.minzoom),
                    czmMaximumLevel: Number(item.maxzoom),
                    czmTileWidth: Number(item.tilesize),
                    czmTileHeight: Number(item.tilesize)
                }
                newList.push(li)
            })
            models.forEach((item: modelType) => {
                const li: imageServe = {
                    type: '模型',
                    name: item.name,
                    serverUrl: (`${cesiumLabUrl.value}/tile/model/service/${item.id}/tileset.json`),
                    createTime: item.createTime,
                    MaximumLevel: 0,
                    geographicalScope: ''
                }
                newList.push(li)
            })
            terrains.forEach((item: terrainType) => {
                const li: imageServe = {
                    type: '地形',
                    name: item.name,
                    serverUrl: (`${cesiumLabUrl.value}/tile/terrain/${item.id}`),
                    createTime: item.createTime,
                    MaximumLevel: item.maxzoom,
                    geographicalScope: `${item.west.toFixed(4)}，${item.south.toFixed(4)}，${item.east.toFixed(4)}，${item.north.toFixed(4)}`,
                    rectangle: [item.west, item.south, item.east, item.north]
                }
                newList.push(li)
            })
            serverList.value = newList
        }
    })).catch(error => {
        console.log(error);
        serverList.value = []
        Message.warning('未请求到数据，请检查')

    })
}
const changeToken = () => {
    tokenInputShow.value = false
    initNewList()
}
onMounted(() => {
    initNewList()
})
</script>